package com.example.im.server.im

import android.text.TextUtils
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMDirect
import cc.vv.lkimcomponent.lkim.operate.LKIMEdit
import com.example.im.SKIMSend
import com.example.util.finallist.IMExtKey
import com.example.util.finallist.SkKey

/**
 * @author  chaohaipeng  on 2018/7/23.
 */
class MessageHandleServer {
    private object mHolder {
        val instance = MessageHandleServer()
    }
    companion object {
        fun getInstance(): MessageHandleServer {
            return mHolder.instance
        }
    }

    /**
     * 设置已读
     */
    fun messageAck( mIMMessage: LKIMMessage) {
        try {
            if (null != mIMMessage && LKIMDirect.RECEIVE == mIMMessage.getLKIMDirect()) {
                if (LKIMChatType.SingleChat == mIMMessage.getLKIMChatType()) {
                    /**
                     * 单聊不做判断,只要阅读就调用已读回执
                     */
                    LKIMEdit.getInstance().ackRead(mIMMessage.getFromAccount(), mIMMessage.getMsgId())
                } else {
                    /**
                     * 群聊先做已读未读判断,未读情况下调用ack透传通知对方已读
                     */
                    val readStatus = mIMMessage.getAttribute(IMExtKey.EXTKEY_READSTATUS, SkKey.BTKEY_String_0)
                    if (TextUtils.equals(SkKey.BTKEY_String_0, readStatus)) {
                        mIMMessage.setAttribute(IMExtKey.EXTKEY_READSTATUS, SkKey.BTKEY_String_1)
                        /**
                         * 同步消息到数据库
                         */
                        LKIMEdit.getInstance().update(mIMMessage.getToAccount(), mIMMessage)
                        SKIMSend.getInstance().cmdAckRead(mIMMessage.getToAccount(), mIMMessage, LKIMChatType.GroupChat, object : SKIMSend.CmdSendInter{
                            override fun onSuccess(lkimMessage: LKIMMessage) {

                            }

                            override fun faile(lkimMessage: LKIMMessage) {
                                mIMMessage.setAttribute(IMExtKey.EXTKEY_READSTATUS, SkKey.BTKEY_String_0)
                                LKIMEdit.getInstance().update(mIMMessage.getToAccount(), mIMMessage)
                            }
                        })
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }


}